﻿using System;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace FluentDml.Tests
{
    /// <summary>
    /// based on http://www.dotnetguy.co.uk/post/2009/10/20/sqlite-nunit-fluent-nhibernate-test-your-data-access-layer
    /// </summary>
    public class InMemoryDatabase : IDisposable
    {
        private static Configuration configuration;
        private static ISessionFactory sessionFactory;

        public ISession Session { get; set; }

        public InMemoryDatabase()
        {
            sessionFactory = CreateSessionFactory();
        }

        public void CreateSession()
        {
            Session = sessionFactory.OpenSession();
            BuildSchema(Session);
        }

        public void TearDownSession()
        {
            Session.Dispose();
        }

        public void Dispose()
        {
            sessionFactory.Dispose();
        }


        private static ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
                .Database(SQLiteConfiguration.Standard.InMemory().ShowSql())
                .Mappings(M => M.FluentMappings.AddFromAssemblyOf<InMemoryDatabase>())
                .ExposeConfiguration(Cfg => configuration = Cfg)
                .BuildSessionFactory();
        }
        private static void BuildSchema(ISession session)
        {
            SchemaExport export = new SchemaExport(configuration);
            export.Execute(true, true, false, session.Connection, null);
            session.Flush();

        }
    }
}